import EventApi from "@module/EventApi";
import Icon from "@ui/RJMart/icons";
export default function AccountManage(props) {
    // console.log(props);
    const userObj = props.user;
    let currentSelectIndex, defaultSelectIndex;

    function hideDialog(e) {
        if (!e || e.target.id != "toggleAccount") {
            EventApi.emit("showShiftAccount", false);
        }
    }

    React.useEffect(() => {
        window.addEventListener("click", hideDialog);
        return () => {
            window.removeEventListener("click", hideDialog);
        };
    });

    function refreshCookieByFieldName(data, fieldName) {
        fieldName = fieldName || "user";
        Uts.setCookieMt({
            id: data[fieldName].id,
            username: data[fieldName].realName,
            organization: data[fieldName].organization.name,
            orgId: data[fieldName].organization.id,
            vm: data[fieldName].mobile,
            userEmail: data[fieldName].email,
            orgCode: data[fieldName].organization.code
        });
        if (data[fieldName].departments.length > 0) {
            Uts.setCookie("deptId", data[fieldName].departments[0].id);
        } else {
            Uts.setCookie("deptId", "");
        }
    }

    function selectCurrent(obj, index) {
        // console.log(obj, index);
        let currentId = obj.id;
        let reqData = {
            orgId: currentId,
            isUpdateAccounts: true,
            isDefaultOrg: false
        };
        if (currentId != Uts.getCookie("orgId")) {
            REST.post("/store/api/accounts/" + currentId, {}, "noInfo").then(
                function(data) {
                    if (data.code === "0000") {
                        //1.set cookie
                        Uts.storage.set(
                            "STORE_USERPERMISSION",
                            Uts.fetchObjectArrayToStringArray(
                                data.user.permissions,
                                "name"
                            )
                        );
                        refreshCookieByFieldName(data);
                        // UserApi.updateUserState(data.user);
                        // hideDialog();
                        location.reload();
                        //
                    } else {
                        //show message
                    }
                },
                function(error) {
                    //console.log(error);
                }
            );
        }
    }
    function setDefault(obj, index) {
        // console.log(obj, index);
        var id = obj.id;
        var reqData = {
            orgId: id,
            isUpdateAccounts: false,
            isDefaultOrg: true
        };
        REST.post(
            "/store/api/user/buyer/settingDefaultOrg",
            reqData,
            "getInfo"
        ).then(
            function(data) {
                if (data.code === "0000") {
                    obj.defaultOrg = true;
                    refreshCookieByFieldName(data, "storeSecurityUser");
                    UserApi.updateUserState(data.storeSecurityUser);
                    // hideDialog();
                } else {
                    //show message
                }
            },
            function(error) {
                //console.log(error);
            }
        );
    }
    function setDefaultIndex(index) {
        userObj.$$defaultIndex = index;
    }
    return (
        <div
            id="AccountManageWrap"
            className=" zen_w-273 zen_ps-ab zen_t-25 zen_z-i-1 zen_bd-D1D1D1 zen_bg-white "
        >
            <div className="zen_bg-gray  zen_p-v-6 zen_p-h-12 zen_c-a">
                请选择需要切换的单位
            </div>
            <ul className="zen_h-112 zen_of-y-a">
                {userObj.orgs.map(function(obj, index) {
                    return (
                        <li
                            onClick={() => {
                                selectCurrent(obj, index);
                            }}
                            key={obj.id}
                            className={Uts.sc([
                                index == 0 ? "zen_p-t-12" : "",
                                obj.id,
                                "zen_p-v-6 zen_p-h-12 zen_hover-wrap zen_ps-re"
                            ])}
                        >
                            {obj.name + (obj.defaultOrg ? "(默认)" : "")}
                            {obj.id == Uts.getCookie("orgId") && (
                                <span
                                    className={Uts.sc([
                                        "selected zen_ps-ab zen_r-12 zen_t-2",
                                        index == 0 ? "zen_t-8" : ""
                                    ])}
                                >
                                    <Icon
                                        type={"check"}
                                        color={""}
                                        width="20"
                                        height="20"
                                    />
                                </span>
                            )}
                            {obj.defaultOrg && setDefaultIndex(index)}
                            {!obj.defaultOrg && (
                                <span
                                    onClick={e => {
                                        e.stopPropagation();
                                        setDefault(obj, index);
                                    }}
                                    className={Uts.sc([
                                        "zen_ps-ab zen_r-12 zen_t-6 main-color zen_hover-show zen_bg-white zen_z-i-2",
                                        index == 0 ? "zen_t-12" : ""
                                    ])}
                                >
                                    设为默认
                                </span>
                            )}
                        </li>
                    );
                })}
            </ul>
        </div>
    );
}
